<template>
    <div class="app-container">
        <el-container>
            <el-container style="border: 1px solid #eee">
                <el-header style="text-align: left">
                    <span>用户列表</span>
                </el-header>
                <el-main>
                    <el-form :inline="true" class="demo-form-inline">
                        <el-form-item>
                            <el-button v-if="hasPerm('sys:user:add')"
                                       type="success"
                                       plain
                                       icon="el-icon-circle-plus-outline"
                                       size="mini"
                                       @click="openAddUser"
                            >新增
                            </el-button
                            >
                            <el-button v-if="hasPerm('sys:user:edit')"
                                       type="primary"
                                       plain
                                       icon="el-icon-edit"
                                       size="mini"
                                       @click="openEditUser"
                            >编辑
                            </el-button
                            >
                            <el-button v-if="hasPerm('sys:user:delete')"
                                       type="danger"
                                       plain
                                       icon="el-icon-delete"
                                       size="mini"
                                       @click="deleteUser"
                            >删除
                            </el-button
                            >
                            <el-button v-if="hasPerm('sys:user:resetPassword')"
                                       type="warning"
                                       plain
                                       icon="el-icon-key"
                                       size="mini"
                                       @click="openResetPwd"
                            >重置密码
                            </el-button
                            >
                        </el-form-item>
                        <el-form-item>
                            <el-input
                                    placeholder="用户名/名称"
                                    size="mini"
                                    clearable
                                    v-model.trim="key"
                                    @keyup.enter.native="getList"
                            ></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button v-if="hasPerm('sys:user:query')"
                                       type="primary"
                                       icon="el-icon-search"
                                       plain
                                       size="mini"
                                       @click="getList"
                            >查询
                            </el-button
                            >
                            <el-button v-if="hasPerm('sys:user:query')"
                                       type="info"
                                       icon="el-icon-refresh"
                                       plain
                                       size="mini"
                                       @click="resetData"
                            >重置
                            </el-button
                            >
                        </el-form-item>
                    </el-form>

                    <el-table
                            :data="hasPerm('sys:user:query')?list:[]"
                            height="440"
                            ref="selectUser"
                            :highlight-current-row="true"
                            @selection-change="userChange"
                            @row-click="userClick"
                    >
                        <!-- <el-table-column type="selection" align="center"> </el-table-column> -->
                        <el-table-column label="序号" width="50" align="center">
                            <template slot-scope="scope">
                                {{ (page - 1) * limit + scope.$index + 1 }}
                            </template>
                        </el-table-column>

                        <el-table-column align="center" label="id" v-if="false" prop="id">
                        </el-table-column>

                        <el-table-column align="left" label="用户名" prop="code">
                        </el-table-column>
                        <el-table-column align="left" label="姓名" prop="name">
                        </el-table-column>
                        <el-table-column align="left" label="账号状态" prop="status"
                                         :formatter="(row,column)=>{
                                            switch (row.status) {
                                              case 0:return '正常'
                                              case 1:return '停用'
                                              case 1:return '锁住'
                                              default:return ''
                                            }
                                         }"
                        ></el-table-column>
                        <el-table-column align="left" label="在线状态" prop="onlineFlag"
                                         :formatter="(row,column)=>{
                                            switch (row.onlineFlag) {
                                              case 0:return '在线'
                                              case 1:return '下线'
                                              default:return ''
                                            }
                                         }"
                        ></el-table-column>
                        <el-table-column align="left" label="创建时间" prop="createTime" :formatter="formatDate" width="140"
                        ></el-table-column>
                        <el-table-column align="left" label="最近登录时间" prop="lastLoginTime" :formatter="formatDate"
                                         width="140"
                        ></el-table-column>

                    </el-table>
                    <el-pagination
                            background
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :current-page="page"
                            :page-sizes="[8, 15, 30, 50]"
                            :page-size="limit"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="parseInt(total)"
                    >
                    </el-pagination>
                </el-main>
            </el-container>
            <el-container style="border: 1px solid #eee">
                <el-header style="text-align: left">
                    <span>拥有角色列表</span>
                </el-header>
                <el-main>
                    <el-form :inline="true" class="demo-form-inline">
                        <el-form-item>
                            <el-button v-if="hasPerm('sys:user:addUR') && hasPerm('sys:role:query')"
                                       type="success"
                                       icon="el-icon-circle-plus-outline"
                                       plain
                                       size="mini"
                                       @click="openAddUserRole"
                            >分配角色
                            </el-button
                            >
                        </el-form-item>
                    </el-form>
                    <el-table
                            :data="hasPerm('sys:user:role:query')?userRoleList:[]"
                            height="440"
                    >
                        <el-table-column label="序号" width="50" align="center" type="index">
                        </el-table-column>

                        <el-table-column label="角色id" v-if="false" prop="id">
                        </el-table-column>

                        <el-table-column align="center" label="角色名称" prop="name">
                        </el-table-column>
                    </el-table>
                </el-main>
            </el-container>
        </el-container>
        <!--新增和编辑窗口 -->
        <el-dialog
                :visible.sync="dialogVisible"
                :title="dialogType === 'edit' ? '编辑用户' : '新增用户'"
                width="400px"
        >
            <el-form
                    :model="user"
                    label-width="80px"
                    label-position="right"
                    :rules="rules"
                    ref="userForm"
                    size="mini"
            >
                <el-form-item label="用户名" prop="code">
                    <el-input v-model="user.code" placeholder="请输入用户名" :disabled="dialogType==='edit'"/>
                </el-form-item>
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="user.name" placeholder="请输入名称"/>
                </el-form-item>
                <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
                    <el-input type="password" v-model="user.password" placeholder="请输入密码"/>
                </el-form-item>
                <el-form-item label="确认密码" prop="password2" v-if="dialogType === 'add'">
                    <el-input type="password" v-model="user.password2" placeholder="请输入密码"/>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="user.phone" placeholder="请输入手机号"/>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input type="email" v-model="user.email" placeholder="请输入邮箱"/>
                </el-form-item>

            </el-form>
            <div style="text-align: right">
                <el-button type="danger" size="mini" @click="dialogVisible = false"
                >取消
                </el-button
                >
                <el-button type="primary" size="mini" @click="confirmForm('userForm')"
                >确认
                </el-button
                >
            </div>
        </el-dialog>

        <el-dialog
                :visible.sync="roleVisible"
                title="选择角色"
                width="400px"
        >
            <el-table
                    :data="roleList"
                    height="300"
                    ref="selectRole"
                    :highlight-current-row="true"
                    @selection-change="roleChange"
                    @row-click="roleClick"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column label="序号" width="50" align="center" type="index">
                </el-table-column>

                <el-table-column align="center" label="id" v-if="false" prop="id">
                </el-table-column>

                <el-table-column align="left" label="角色名称" prop="name">
                </el-table-column>
            </el-table>
            <div style="text-align: right">
                <el-button type="danger" @click="roleVisible = false">取消</el-button>
                <el-button type="primary" @click="insertUserRole">确认</el-button>
            </div>
        </el-dialog>

        <el-dialog
                :visible.sync="resetPwdVisible"
                title="重置密码"
                width="400px"
        >
            <el-form :model="user"
                     label-width="80px"
                     label-position="right"
                     size="mini">
                <el-form-item label="新密码">
                    <el-input type="password" v-model="user.password" placeholder="请输入新密码"/>
                </el-form-item>
            </el-form>
            <div style="text-align: right">
                <el-button type="danger" @click="resetPwdVisible = false">取消</el-button>
                <el-button type="primary" @click="resetPwd">确认</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>

    import userApi from '@/api/sys/user'
    import roleApi from '@/api/sys/role'
    import * as DateUtil from '../../../utils'

    const defaultModel = {
        id: null,
        name: null,
        code: null,
        password: null,
        password2: null,
        phone: null,
        email: null
    }
    export default {
        //写核心代码位置
        data() {
            let validatePassword = (rule, value, callback) => {
                if (value && value === '') {
                    callback(new Error('请输入密码'))
                } else {
                    if (this.user.password2 !== '') {
                        this.$refs.userForm.validateField('password2')
                    }
                    callback()
                }
            }
            let validatePassword2 = (rule, value, callback) => {
                if (value && value === '') {
                    callback(new Error('请再次输入密码'))
                } else if (value !== this.user.password) {
                    callback(new Error('两次输入密码不一致!'))
                } else {
                    callback()
                }
            }
            let validatePhone = (rule, value, callback) => {
                if (value && value !== '') {
                    if (!(/^1[3456789]\d{9}$/.test(value))) {
                        callback(new Error('手机号不合法'))
                    }
                }
                callback()
            }
            let validateEmail = (rule, value, callback) => {
                if (value && value !== '') {
                    if (!(/^\w+((.\w+)|(-\w+))@[A-Za-z0-9]+((.|-)[A-Za-z0-9]+).[A-Za-z0-9]+$/.test(value))) {
                        callback(new Error('邮箱不合法'))
                    }
                }
                callback()
            }
            //定义变量和初始值
            return {
                user: Object.assign({}, defaultModel),
                dialogVisible: false,
                dialogType: 'add',
                list: [], //查询之后接口返回集合
                key: '',
                selectUser: [],
                userRoleList: [],
                page: 1, //当前页
                limit: 8, //每页记录数
                total: 0, //总记录数
                roleList: [],
                roleVisible: false,
                selectRole: [],

                resetPwdVisible: false,//重置密码

                rules: {
                    code: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
                    name: [{ required: true, message: '请输入用户名称', trigger: 'blur' }],
                    password: [
                        { validator: validatePassword, trigger: 'blur', required: true }
                    ],
                    password2: [
                        { validator: validatePassword2, trigger: 'blur', required: true }
                    ],
                    phone: [{ validator: validatePhone, trigger: 'blur' }],
                    email: [{ validator: validateEmail, trigger: 'blur' }]
                }
            }
        },
        created() {
            this.getList()
        },
        methods: {
            handleSizeChange(val) {
                this.limit = val
                this.getList()
            },
            handleCurrentChange(val) {
                this.page = val
                this.getList()
            },

            getList() {
                userApi.getList(this.key, this.page, this.limit).then((response) => {
                    this.list = response.data.list
                    this.total = response.data.total
                })
            },
            resetData() {
                this.selectUser = []
                this.userRoleList = []
                this.key = ''
                this.getList()
            },

            openAddUser() {
                this.user = Object.assign({}, defaultModel)
                this.dialogType = 'add'
                this.dialogVisible = true
            },

            openEditUser() {
                if (this.selectUser.length !== 1) {
                    this.$message({
                        showClose: true,
                        message: '请选择用户',
                        type: 'warning'
                    })
                    return
                }
                this.user = Object.assign({}, this.selectUser[0])
                this.dialogType = 'edit'
                this.dialogVisible = true
            },

            confirmForm(formName) {
                const isEdit = this.dialogType === 'edit'
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        if (isEdit) {
                            userApi.update(this.user).then((response) => {
                                //请求成功
                                this.$message({
                                    type: 'success',
                                    message: '修改成功!'
                                })
                                for (let index = 0; index < this.list.length; index++) {
                                    if (this.list[index].id === this.user.id) {
                                        this.list.splice(index, 1, this.user)
                                        break
                                    }
                                }
                                this.dialogVisible = false
                            })
                        } else {
                            userApi.insert(this.user).then((response) => {
                                this.$message({
                                    type: 'success',
                                    message: '添加成功!'
                                })
                                this.dialogVisible = false
                                this.getList()
                            })
                        }
                    } else {
                        return false
                    }
                })
            },

            openResetPwd() {
                if (this.selectUser.length !== 1) {
                    this.$message({
                        showClose: true,
                        message: '请选择一个用户',
                        type: 'warning'
                    })
                    return
                }
                this.resetPwdVisible = true
                this.user = Object.assign({}, defaultModel)
            },

            resetPwd() {
                if (this.user.password === '' || this.user.password == null) {
                    this.$message({
                        showClose: true,
                        message: '请输入密码',
                        type: 'warning'
                    })
                    return
                }
                this.user.id = this.selectUser[0].id
                userApi.resetPwd(this.user).then(() => {
                    this.resetPwdVisible = false
                    this.$message({
                        showClose: true,
                        message: '重置成功',
                        type: 'success'
                    })
                    this.getList()
                })

            },

            deleteUser() {
                if (this.selectUser.length !== 1) {
                    this.$message({
                        showClose: true,
                        message: '请选择一个用户',
                        type: 'warning'
                    })
                    return
                }
                this.$confirm('此操作将永久删除记录, 是否继续?', '提示', {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    userApi.delete(this.selectUser[0].id).then((response) => {
                        this.$message({
                            showClose: true,
                            message: '删除成功',
                            type: 'success'
                        })
                        this.getList()
                    })
                })
            },

            openAddUserRole() {
                if (this.selectUser.length !== 1) {
                    this.$message({
                        showClose: true,
                        message: '请选择用户',
                        type: 'warning'
                    })
                    return
                }
                roleApi.getList().then((response) => {
                    this.roleList = response.data
                    this.roleVisible = true
                    this.$nextTick(() => {
                        this.$refs.selectRole.clearSelection()
                        for (let i = 0; i < this.roleList.length; i++) {
                            for (let j = 0; j < this.userRoleList.length; j++) {
                                if (this.roleList[i].id === this.userRoleList[j].id) {
                                    this.$refs.selectRole.toggleRowSelection(this.roleList[i])
                                }
                            }
                        }
                    })
                })

            },

            getUserRoleList() {
                if (this.selectUser.length !== 1) {
                    this.$message({
                        showClose: true,
                        message: '请选择用户',
                        type: 'warning'
                    })
                    return
                }
                userApi.getRoleListByUser(this.selectUser[0].id).then((response) => {
                    this.userRoleList = response.data
                })
            },

            insertUserRole() {
                let data = {
                    userId: this.selectUser[0].id,
                    roleList: this.selectRole
                }
                userApi.insertUserRole(data).then((response) => {
                    this.roleVisible = false
                    this.getUserRoleList()
                    this.$message({
                        message: '分配成功',
                        type: 'success'
                    })
                })
            },

            /**
             * 当选择改变时
             */
            userChange(val) {
                let me = this
                me.selectUser = val
            },

            /**点击 */
            userClick(row) {
                let me = this
                me.$refs.selectUser.clearSelection()
                me.$refs.selectUser.toggleRowSelection(row, true)
                me.getUserRoleList()
            },
            /**
             * 当选择改变时
             */
            roleChange(val) {
                let me = this
                me.selectRole = val
            },

            /**点击 */
            roleClick(row) {
                let me = this
                // me.$refs.selectRole.clearSelection()
                me.$refs.selectRole.toggleRowSelection(row)
            },
            /**格式化*/
            formatDate(row, column) {
                let val = Number.parseInt(row[column.property])
                if (val) {
                    return DateUtil.formatDate(val, 'yyyy-MM-dd HH:mm:ss')
                }
                return ''

            }
        }
    }
</script>
